package com.yiwei.zxp.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.bumptech.glide.Glide;
import com.yiwei.zxp.R;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.ShopAddBean;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.constant.UserInfoGlobal;
import com.yiwei.zxp.event.ShopCartEvent;
import com.yiwei.zxp.util.Dialog;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.QRCode;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.Spans;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class MyQrCodeActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.img_icon)
    ImageView imgIcon;
    @BindView(R.id.txt_name)
    TextView txtName;
    @BindView(R.id.img_code)
    ImageView imgCode;
    @BindView(R.id.layout_code)
    LinearLayout layoutCode;
    @BindView(R.id.btn_reset)
    SuperButton btnReset;

    private Unbinder unbiner;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_qrcode);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("二维码名片");
        Glide.with(this).load(UserInfoGlobal.getIcon()).asBitmap().error(R.mipmap.img_my_default).into(imgIcon);
        if (!TextUtils.isEmpty(UserInfoGlobal.hasInviteCode())) {
            Spanned txt_info = Spans.with(this).font(UserInfoGlobal.getUserName(), getResources().getDimensionPixelSize(R.dimen.x34), 0xff000000).style(Typeface.BOLD).
                    font("\n我的邀请码：" + UserInfoGlobal.hasInviteCode(), getResources().getDimensionPixelSize(R.dimen.x28), 0xff999999).
                    build();
            txtName.setText(txt_info);
        } else {
            getInviteCode();
        }
        getQrcodeLink();

        imgCode.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                Dialog.showDefaultDialog(MyQrCodeActivity.this, "", "是否保存二维码?", "取消", "保存", false, new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {
                        checkPermission(new CheckPermListener() {
                            @Override
                            public void superPermission() {
                                saveImageToGallery(MyQrCodeActivity.this, ((BitmapDrawable) imgCode.getDrawable()).getBitmap());
                            }

                        }, R.string.camera_storage_card_p, R.string.ask_again, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    }

                    @Override
                    public void cancel() {

                    }
                });
                return false;
            }
        });
    }

    public void getInviteCode() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getSetInvitecode().compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Spanned txt_info = Spans.with(this).font(UserInfoGlobal.getUserName(), getResources().getDimensionPixelSize(R.dimen.x34), 0xff000000).style(Typeface.BOLD).
                            font("\n我的邀请码：" + result.datas.invite_code, getResources().getDimensionPixelSize(R.dimen.x28), 0xff999999).
                            build();
                    txtName.setText(txt_info);
                });
    }

    public void getQrcodeLink() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getQrcodeLink().compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Glide.with(this).load(result.datas.url).asBitmap().into(imgCode);
//                    imgCode.setImageBitmap(QRCode.createQRCode(result.datas.url));
                });
    }

    public void getResetQrcode() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getResetQrcode().compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "重置成功");
                    Glide.with(this).load(result.datas.url).asBitmap().into(imgCode);
//                    imgCode.setImageBitmap(QRCode.createQRCode());
                });
    }

    public static void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "hmx");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
        ToastUtil.makeText(context, "保存成功").show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.btn_back, R.id.btn_reset})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_reset:
                Dialog.showDefaultDialog(this, "", "重置后你将会获得新的二维码", "取消", "重置", false, new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {
                        getResetQrcode();
                    }

                    @Override
                    public void cancel() {

                    }
                });
                break;
        }
    }
}
